﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using Microsoft.AspNet.SignalR;
using System.Text;

namespace EyeOfTheWorld
{
    public class Control : Hub
    {
        public void Eye(string address, int depth, int namesLevel)
        {
            if (!address.StartsWith("http://"))
            {
                address = "http://" + address;
            }
            try
            {
                WebRequest req = WebRequest.Create(address);
                WebResponse res = req.GetResponse();
                WebSpider spider = new WebSpider();
                string data = spider.GetData(res.ResponseUri.AbsoluteUri, depth, namesLevel);
                Clients.Caller.graphUpdate(data);
            }
            catch (WebException e)
            {
                Clients.Caller.graphUpdate(string.Format("bad|bad|6|address|address|5|!|!|4|please|please|0|enter|enter|1|a valid|a valid|4|one|one|6|error|{0}|6$0|1|1|2|3|4|4|5|5|6|2|3|6|7", e.Message));
            }
            catch (UriFormatException)
            {
                Clients.Caller.graphUpdate("please|please|6|enter|enter|5|an|an|4|address|address|0|in|in|1|the|the|4|menu|menu|6|above|above|6$0|1|1|2|3|4|4|5|5|6|2|3|6|7");
            }
            catch (Exception e)
            {
                Clients.Caller.graphUpdate(string.Format("error|{0}|6$", e.Message));
            }
        }

        public void Reveal(string root, int depth, int namesLevel)
        {
            if (root == "undefined")
            {
                Clients.Caller.graphUpdate("please|please|0|choose|choose|1|a|a|2|root|root|3|from|from|0|the menu|the menu|1|above|above|4$0|1|1|2|2|3|3|4|4|5|5|6");
            }
            else
            {
                if (depth != 0)
                {
                    Database db = Database.Instance;
                    Restore(db);
                    Oracle oracle = new Oracle();
                    string data = oracle.Reveal(root, depth, namesLevel);
                    Clients.Caller.graphUpdate(data);
                    db.Obliviate();
                }
                else
                {
                    Clients.Caller.graphUpdate(string.Format("{0}|{1}|0$", root, root));
                }
            }
        }
  
        public void Restore(Database db)
        {
            if (db.allPages.Count == 0)
            {
                string[] allPages = DB.allPages;
                string[] allLinks = DB.allLinks;
                foreach (string page in allPages)
                {
                    db.AddPage(page);
                }
                for (int link = 0; link < allLinks.Length; )
                {
                    db.AddLink(allLinks[link++], allLinks[link++], allLinks[link++]);
                }
            }
        }
    }
}